package com.sfac.springCloudAccount.service.impl;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;
import com.sfac.springCloudAccount.dao.ResourceDao;
import com.sfac.springCloudAccount.dao.RoleResourceDao;
import com.sfac.springCloudAccount.service.ResourceService;
import org.sfac.account.entity.Resource;
import org.sfac.account.entity.RoleResource;
import org.sfac.common.vo.Result;
import org.sfac.common.vo.Search;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;


@Service
public class ResourceServiceImpl implements ResourceService {
	
	@Autowired
	private ResourceDao resourceDao;
	@Autowired
	private RoleResourceDao roleResourceDao;

	@Override
	@Transactional
	public Result<Resource> insertResource(Resource resource) {
		resource.setCreateDate(LocalDateTime.now());
		resource.setUpdateDate(LocalDateTime.now());
		resourceDao.insertResource(resource);
		if (resource.getRoles() != null) {
			resource.getRoles().stream()
				.forEach(item -> {
					roleResourceDao.insertRoleResource(
							new RoleResource(item.getId(), resource.getId()));
				});
		}
		return new Result<Resource>(Result.ResultStatus.SUCCESS.code,
				"Insert success", resource);
	}

	@Override
	@Transactional
	public Result<Resource> updateResource(Resource resource) {
		resourceDao.updateResource(resource);
		roleResourceDao.deleteRoleResourceByResourceId(resource.getId());
		if (resource.getRoles() != null) {
			resource.getRoles().stream()
				.forEach(item -> {roleResourceDao.insertRoleResource(new RoleResource(item.getId(), resource.getId()));});
		}
		return new Result<Resource>(Result.ResultStatus.SUCCESS.code,
				"Update success", resource);
	}
	
	@Override
	@Transactional
	public Result<Object> deleteResourceById(int id) {
		resourceDao.deleteResourceById(id);
		roleResourceDao.deleteRoleResourceByResourceId(id);
		return new Result<Object>(Result.ResultStatus.SUCCESS.code, "Delete success");
	}

	@Override
	public Resource getResourceById(int id) {
		return resourceDao.getResourceById(id);
	}

	@Override
	public List<Resource> getResourcesByRoleId(int roleId) {
		return resourceDao.getResourcesByRoleId(roleId);
	}

	@Override
	public PageInfo<Resource> getResourcesBySearchBean(Search search) {
		search.init();
		PageHelper.startPage(search.getCurrentPage(), search.getPageSize());
		return new PageInfo<Resource>(Optional
				.ofNullable(resourceDao.getResourcesBySearchBean(search))
				.orElse(Collections.emptyList()));
	}

}
